package com.inputabc.ct.v1.util;

import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

/**
 * DeepSeek翻译工具类 - 提供免费AI智能翻译
 * @author AI
 */
public class DeepSeekUtils {
    // DeepSeek API密钥
    public static String API_KEY = "";
    
    // 语言代码常量
    public static final String AUTO = "auto";
    public static final String CHINESE = "zh";
    public static final String ENGLISH = "en";
    public static final String JPANESE = "ja";
    public static final String KOREAN = "ko";
    public static final String FRENCH = "fr";
    public static final String GERMAN = "de";
    public static final String SPANISH = "es";
    public static final String RUSSIAN = "ru";
    
    // DeepSeek API端点
    private static final String API_ENDPOINT = "https://api.deepseek.com/v1/chat/completions";
    
    // 减少连接和读取超时时间
    private static final int CONNECTION_TIMEOUT = 10000;
    
    // 减少读取超时时间
    private static final int READ_TIMEOUT = 15000;

    // 扩展缓存容量并增加缓存生命周期
    private static final Map<String, CachedTranslation> translationCache = new ConcurrentHashMap<>(500);
    
    // 添加缓存对象类，包含过期时间
    private static class CachedTranslation {
        final String translation;
        final long timestamp;
        
        CachedTranslation(String translation) {
            this.translation = translation;
            this.timestamp = System.currentTimeMillis();
        }
        
        boolean isExpired() {
            return System.currentTimeMillis() - timestamp > CACHE_EXPIRY;
        }
    }
    
    // 增加缓存有效期，提高缓存利用率
    private static final long CACHE_EXPIRY = TimeUnit.DAYS.toMillis(7);
    
    // 并行处理的线程池
    private static final ExecutorService TRANSLATION_EXECUTOR = Executors.newFixedThreadPool(
        Math.max(2, Runtime.getRuntime().availableProcessors() / 2)
    );
    
    // 缓存键生成器
    private static String generateCacheKey(String text, String sourceLanguage, String targetLanguage) {
        return sourceLanguage + "_" + targetLanguage + "_" + text.hashCode();
    }
    
    /**
     * 获取离线翻译结果
     * 扩展的常用词汇表，用于在API不可用时提供基本翻译
     */
    private static String getOfflineTranslation(String text, String sourceLanguage, String targetLanguage) {
        // 英译中的常见短语
        if (sourceLanguage.equals(ENGLISH) && targetLanguage.equals(CHINESE)) {
            if (text.equalsIgnoreCase("hello")) return "你好";
            if (text.equalsIgnoreCase("thank you")) return "谢谢";
            if (text.equalsIgnoreCase("sorry")) return "对不起";
            if (text.equalsIgnoreCase("goodbye")) return "再见";
            if (text.equalsIgnoreCase("yes")) return "是";
            if (text.equalsIgnoreCase("no")) return "否";
            if (text.equalsIgnoreCase("please")) return "请";
            if (text.equalsIgnoreCase("welcome")) return "欢迎";
        } 
        // 中译英的常见短语
        else if (sourceLanguage.equals(CHINESE) && targetLanguage.equals(ENGLISH)) {
            if (text.equals("你好")) return "hello";
            if (text.equals("谢谢")) return "thank you";
            if (text.equals("对不起")) return "sorry";
            if (text.equals("再见")) return "goodbye";
            if (text.equals("是")) return "yes";
            if (text.equals("否")) return "no";
            if (text.equals("请")) return "please";
            if (text.equals("欢迎")) return "welcome";
        }
        // 日译中的常见短语
        else if (sourceLanguage.equals(JPANESE) && targetLanguage.equals(CHINESE)) {
            if (text.equals("こんにちは")) return "你好";
            if (text.equals("ありがとう")) return "谢谢";
            if (text.equals("さようなら")) return "再见";
        }
        // 中译日的常见短语
        else if (sourceLanguage.equals(CHINESE) && targetLanguage.equals(JPANESE)) {
            if (text.equals("你好")) return "こんにちは";
            if (text.equals("谢谢")) return "ありがとう";
            if (text.equals("再见")) return "さようなら";
        }
        
        return null;
    }
    
    /**
     * 用于避免对非常简单的短语进行API调用
     */
    private static String quickTranslate(String text, String sourceLanguage, String targetLanguage) {
        // 英译中的常见短语
        if (sourceLanguage.equals(ENGLISH) && targetLanguage.equals(CHINESE)) {
            if (text.equalsIgnoreCase("hello")) return "你好";
            if (text.equalsIgnoreCase("hi")) return "嗨";
            if (text.equalsIgnoreCase("yes")) return "是";
            if (text.equalsIgnoreCase("no")) return "否";
            if (text.equalsIgnoreCase("ok")) return "好的";
        }
        // 中译英的常见短语
        else if (sourceLanguage.equals(CHINESE) && targetLanguage.equals(ENGLISH)) {
            if (text.equals("你好")) return "hello";
            if (text.equals("嗨")) return "hi";
            if (text.equals("是")) return "yes";
            if (text.equals("否")) return "no";
            if (text.equals("好的")) return "ok";
        }
        return null;
    }
    
    /**
     * 清除翻译缓存
     */
    public static void clearCache() {
        translationCache.clear();
    }
    
    /**
     * 获取语言名称
     */
    private static String getLanguageName(String languageCode) {
        switch (languageCode) {
            case CHINESE: return "中文";
            case ENGLISH: return "英文";
            case JPANESE: return "日文";
            case KOREAN: return "韩文";
            case FRENCH: return "法文";
            case GERMAN: return "德文";
            case SPANISH: return "西班牙文";
            case RUSSIAN: return "俄文";
            case AUTO: return "自动检测的语言";
            default: return languageCode;
        }
    }
    
    /**
     * 转义JSON字符串
     */
    private static String escapeJson(String input) {
        if (input == null) {
            return "";
        }
        return input.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t");
    }
    
    /**
     * 使用DeepSeek API进行翻译
     * @param text 要翻译的文本
     * @param sourceLanguage 源语言
     * @param targetLanguage 目标语言
     * @return 翻译结果
     * @throws Exception 如有错误抛出异常
     */
    public static String translate(String text, String sourceLanguage, String targetLanguage) throws Exception {
        return translate(text, sourceLanguage, targetLanguage, false);
    }
    
    /**
     * 使用DeepSeek API进行免费翻译
     * @param text 要翻译的文本
     * @param sourceLanguage 源语言
     * @param targetLanguage 目标语言
     * @return 翻译结果
     * @throws Exception 如有错误抛出异常
     */
    public static String freeTranslate(String text, String sourceLanguage, String targetLanguage) throws Exception {
        return translate(text, sourceLanguage, targetLanguage, true);
    }
    
    /**
     * 使用DeepSeek API进行翻译的内部方法
     * @param text 要翻译的文本
     * @param sourceLanguage 源语言
     * @param targetLanguage 目标语言
     * @param forceFree 是否强制使用免费模式
     * @return 翻译结果
     * @throws Exception 如有错误抛出异常
     */
    private static String translate(String text, String sourceLanguage, String targetLanguage, boolean forceFree) throws Exception {
        // 提前检查空文本
        if (text == null || text.trim().isEmpty()) {
            return "";
        }
        
        // 检查缓存中是否已有该翻译
        String cacheKey = generateCacheKey(text, sourceLanguage, targetLanguage);
        
        // 优化缓存检查
        CachedTranslation cachedResult = translationCache.get(cacheKey);
        if (cachedResult != null) {
            if (!cachedResult.isExpired()) {
                return cachedResult.translation;
            } else {
                // 移除过期缓存
                translationCache.remove(cacheKey);
            }
        }
        
        // 对于非常短的文本，快速处理
        if (text.length() <= 5) {
            String quickResult = quickTranslate(text, sourceLanguage, targetLanguage);
            if (quickResult != null) {
                translationCache.put(cacheKey, new CachedTranslation(quickResult));
                return quickResult;
            }
        }
        
        // 尝试离线翻译 - 优先使用离线翻译提高速度
        String offlineResult = getOfflineTranslation(text, sourceLanguage, targetLanguage);
        if (offlineResult != null) {
            translationCache.put(cacheKey, new CachedTranslation(offlineResult));
            return offlineResult;
        }
        
        if (forceFree || API_KEY == null || API_KEY.isEmpty()) {
            // 使用默认免费API密钥或返回简单的离线翻译
            String offlineMessage = "（DeepSeek API密钥未设置，请在设置中配置API密钥）";
            String basicTranslation = getOfflineTranslation(text, sourceLanguage, targetLanguage);
            if (basicTranslation != null) {
                return basicTranslation;
            }
            // 如果没有离线翻译，返回原文并附加提示信息
            translationCache.put(cacheKey, new CachedTranslation(offlineMessage + text));
            return offlineMessage + text;
        }
        
        // 处理特殊语言代码情况
        String actualSourceLang = sourceLanguage;
        if ("zh".equals(sourceLanguage) || "zh-CN".equals(sourceLanguage)) {
            actualSourceLang = CHINESE;
        }
        
        String actualTargetLang = targetLanguage;
        if ("zh".equals(targetLanguage) || "zh-CN".equals(targetLanguage)) {
            actualTargetLang = CHINESE;
        }
        
        // 如果源语言是自动检测，我们在提示中说明
        String langPrompt = actualSourceLang.equals(AUTO) 
            ? "将以下文本翻译成" + getLanguageName(actualTargetLang)
            : "将以下" + getLanguageName(actualSourceLang) + "翻译成" + getLanguageName(actualTargetLang);
        
        // 构建API请求URL
        URL url = new URL(API_ENDPOINT);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + API_KEY);
        connection.setDoOutput(true);
        
        // 设置连接和读取超时
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        
        // 启用缓存
        connection.setUseCaches(true);
        
        // 构建请求体JSON - 减少返回的token数量以加快响应
        String model = forceFree ? "deepseek-lite" : "deepseek-chat";
        String requestBody = "{"
            + "\"model\": \"" + model + "\","
            + "\"messages\": ["
            + "{\"role\": \"system\", \"content\": \"你是一个专业的翻译助手，只负责翻译文本，不添加任何解释或额外内容。\"},"
            + "{\"role\": \"user\", \"content\": \"" + langPrompt + "：" + escapeJson(text) + "\"}"
            + "],"
            + "\"temperature\": 0.1," // 降低温度提高确定性和速度
            + "\"max_tokens\": " + Math.min(text.length() * 2, 500) + "" // 动态调整token数量
            + "}";
        
        // 发送请求
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }
        
        // 读取响应 - 使用更高效的缓冲区大小
        StringBuilder response = new StringBuilder();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8), 8192)) {
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine);
            }
        } catch (java.net.SocketTimeoutException e) {
            throw new Exception("连接DeepSeek API超时，请检查网络或稍后重试");
        } catch (java.net.ConnectException e) {
            throw new Exception("无法连接到DeepSeek API服务器，请检查网络连接");
        } catch (java.io.IOException e) {
            // 尝试读取错误流
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine);
                }
                // 尝试解析错误响应
                try {
                    JSONObject errorResponse = JSONObject.fromObject(response.toString());
                    if (errorResponse.has("error")) {
                        String errorMessage = errorResponse.getJSONObject("error").optString("message", "未知错误");
                        throw new Exception("DeepSeek API错误: " + errorMessage);
                    }
                } catch (Exception jsonEx) {
                    // 如果无法解析JSON，则抛出原始错误
                }
            } catch (Exception ex) {
                // 如果读取错误流也失败，直接抛出原始错误
            }
            throw new Exception("与DeepSeek API通信失败: " + e.getMessage());
        }
        
        // 解析JSON响应
        JSONObject jsonResponse = JSONObject.fromObject(response.toString());
        String translatedText;
        try {
            translatedText = jsonResponse.getJSONArray("choices")
                                      .getJSONObject(0)
                                      .getJSONObject("message")
                                      .getString("content")
                                      .trim();
        } catch (Exception e) {
            // JSON解析出错，可能是API返回了错误响应
            if (jsonResponse.has("error")) {
                JSONObject error = jsonResponse.getJSONObject("error");
                String errorMessage = error.optString("message", "未知错误");
                throw new Exception("API返回错误: " + errorMessage);
            }
            throw new Exception("无法解析翻译结果: " + e.getMessage());
        }
        
        // 将结果存入缓存
        translationCache.put(cacheKey, new CachedTranslation(translatedText));
        
        return translatedText;
    }
    
    /**
     * 清理过期缓存条目的方法 - 定期调用可优化内存使用
     */
    public static void cleanExpiredCache() {
        translationCache.entrySet().removeIf(entry -> entry.getValue().isExpired());
    }
    
    /**
     * 在应用退出时关闭线程池
     */
    public static void shutdown() {
        TRANSLATION_EXECUTOR.shutdown();
        try {
            if (!TRANSLATION_EXECUTOR.awaitTermination(1, TimeUnit.SECONDS)) {
                TRANSLATION_EXECUTOR.shutdownNow();
            }
        } catch (InterruptedException e) {
            TRANSLATION_EXECUTOR.shutdownNow();
        }
    }

    /**
     * 异步翻译方法
     * 
     * @param text 要翻译的文本
     * @param sourceLanguage 源语言
     * @param targetLanguage 目标语言
     * @return 翻译结果的CompletableFuture
     */
    public static CompletableFuture<String> translateAsync(String text, String sourceLanguage, String targetLanguage) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                return translate(text, sourceLanguage, targetLanguage);
            } catch (Exception e) {
                throw new CompletionException(e);
            }
        }, TRANSLATION_EXECUTOR);
    }
}